<template>
	<view class="p-share">
		<view class="item" v-for="(item, index) in share" :key="item" @tap="fnShare(index)">
			<view class="icon"></view>
			<view class="name">{{ item }}</view>
		</view>
	</view>
</template>

<script>
export default {
	props: {
		image: {
			type: String
		}
	},
	data() {
		return {
			share: ['保存到本地'],    // 分享的节点信息, '微信朋友圈', '微信好友'
		};
	},
	methods: {
		// 分享
		fnShare(i) {
			if (!this.image) return;
			
			// 分享微信
			if (i) {
				uni.share({
					provider: 'weixin',
					type: 2,
					scene: i === 1 ? 'WXSenceTimeline' : 'WXSceneSession',
					imageUrl: this.image
				});
				return;
			}
			
			// #ifdef H5
			this.downloadFile(Date.now(), this.image);
			// #endif

			// #ifndef H5
			uni.saveImageToPhotosAlbum({
				filePath: this.image,
				success: () => {
					this.util.toast('保存成功', 'success');
				},
				fail: () => {
					this.util.toast('保存失败');
				}
			});
			// #endif
		},
		// base64转blob
		base64ToBlob(code) {
			let parts = code.split(';base64,');
			let contentType = parts[0].split(':')[1];
			let raw = window.atob(parts[1]);
			let rawLength = raw.length;
		
			let uInt8Array = new Uint8Array(rawLength);
		
			for (let i = 0; i < rawLength; ++i) {
				uInt8Array[i] = raw.charCodeAt(i);
			}
			return new Blob([uInt8Array], {type: contentType});
		},
		// 下载
		downloadFile(fileName, content) {
			let aLink = document.createElement('a');
			let blob = this.base64ToBlob(content); // new Blob([content]);
			let evt = document.createEvent('HTMLEvents');
			evt.initEvent('click', true, true);// initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
			aLink.download = fileName;
			aLink.href = URL.createObjectURL(blob);
			aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));// 兼容火狐
		}
 	}
}
</script>

<style lang="scss">
.p-share {
	@include flex;
	justify-content: center;
	.item {
		@include flex;
		flex-direction: column;
		width: 33.33%;
		@for $i from 1 through 3 {
			&:nth-child(#{$i}) .icon {
				background-image: url("~@/static/news-share-#{$i}.png");
			}
		}
		transition: opacity .1s;
		&:active {
			opacity: .5;
		}
	}
	.icon {
		width: 60rpx;
		height: 60rpx;
		margin-bottom: 20rpx;
		@include background;
	}
	.name {
		font-size: 24rpx;
	}
}
</style>
